/**
 * Created by Administrator on 2016/7/25.
 */
var express = require("express");
var fs = require("fs");
var bodyParser = require("body-parser");
var request = require("request");
var RestClient = require("node-rest-client").Client;
var async = require("async");

var app = express();

app.engine("html", function(filePath, options, callback){
   fs.readFile(filePath, function(err, content){
      if(err) return callback(new Error(err));
      //console.log(content);
      return callback(null, content.toString());
   });
});
app.set("views", "./views");
app.set("view engine", "html");

app.use(express.static("client"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))


app.get("/", function(req, res){
   res.render("login");
});

app.get("/test", function(req, res){
   res.render("test")
});

app.get("/index", function(req, res){
   res.render("index");
});

app.post("/login", function(req, res){
   var restClient = new RestClient();

   async.waterfall([
       function(callback){
          restClient.get("http://localhost:8080/sc/rest/token", function(body, response){
             console.log(body.toString());
            callback(null, body.toString());
          });
       },
       function(csrf, callback){
          var options = {
             //data:{uname:"zheng", pwd:"hun",_csrf: csrf},
             //headers:{"Content-Type": "application/json"}
          };
          restClient.post("http://localhost:8080/sc/rest/login", options, function(body, response){
             console.log(body.toString());
             callback(null, "done");
          });
       }
   ])
   /*restClient.get("http://localhost:8080/sc/rest/token", function(body, response){
      var options = {
         data:{uname:"zheng", pwd:"hun"},
         headers:{"Content-Type": "application/json"},
      };
      restClient.post("http://localhost:8080/sc/rest/login", options, function(){
         console.log('******************');
      });
   });*/

});

//���������
app.use(function(err, req, res, next){
   console.error(err.stack);
   res.status(500).send('Something broke!');
});

app.listen(3000);